from PySide import QtGui, QtCore
from add_stuff import Ui_AddStuff


class ControlAddStuff(QtGui.QDialog):
    def __init__(self, parent = None, stuff = None):
        super(ControlAddStuff, self).__init__(parent)
        self.ui = Ui_AddStuff()
        self.ui.setupUi(self)
        self.ui.buttonBox.accepted.connect(self.okAddStuff)
        self.ui.buttonBox.rejected.connect(self.cancel)
        self.ui.btnAdd.clicked.connect(self.addStuff)
        self.ui.btnRemove.clicked.connect(self.removeStuff)

        self.parent = parent
        self._initTables(stuff, parent.parent.db)

    def _initTables(self, stuff, db):

        # ЗАПОЛНЕНИЕ ТАБЛИЦЫ С ВЫБРАННЫМИ ТОВАРАМИ

        self.ui.tableCurrent.setColumnCount(6)
        self.ui.tableCurrent.setHorizontalHeaderLabels(['id', 'providerId', 'Наименование', 'Артикул', 'Кол-во', 'number'])

        if type(stuff) != list:
            raise TypeError('Ожидался список.')

        self.ui.tableCurrent.setRowCount(len(stuff))
        i = 0
        for item in stuff:
            if type(stuff) != list:
                raise TypeError('Ожидался список списоков.')
            j = 0
            for col in item:
                self.ui.tableCurrent.setItem(i, j, QtGui.QTableWidgetItem(col))
                j+=1
            i+=1

        self.ui.tableCurrent.setEditTriggers(QtGui.QTableWidget.NoEditTriggers)
        self.ui.tableCurrent.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
        self.ui.tableCurrent.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.ui.tableCurrent.horizontalHeader().setCascadingSectionResizes(True)
        self.ui.tableCurrent.horizontalHeader().setStretchLastSection(True)
        self.ui.tableCurrent.verticalHeader().setVisible(False)

        self.ui.tableCurrent.setColumnHidden(0, True)
        self.ui.tableCurrent.setColumnHidden(1, True)
        self.ui.tableCurrent.setColumnHidden(5, True)

        #ЗАПОЛНЕНИЕ ТАБЛИЦЫ С ТЕКУЩИМИ ТОВАРАМИ

        self.ui.tableAvailable.setColumnCount(len(db.getTable('Товары').columns))
        self.ui.tableAvailable.setHorizontalHeaderLabels([item[1] for item in db.getTable('Товары').columns])

        i = 0
        availableStuff = db.getTable('Товары').getAllRows()
        self.ui.tableAvailable.setRowCount(len(availableStuff))
        currentIds = [self.ui.tableCurrent.item(i, 0).text() for i in range(0, self.ui.tableCurrent.rowCount())]
        for item in availableStuff:
            if str(item[0]) not in currentIds:
                j = 0
                for col in item:
                    self.ui.tableAvailable.setItem(i, j, QtGui.QTableWidgetItem(col.__str__()))
                    j+=1
                i+=1
            else:
                self.ui.tableAvailable.setRowCount(self.ui.tableAvailable.rowCount()-1)

        self.ui.tableAvailable.setEditTriggers(QtGui.QTableWidget.NoEditTriggers)
        self.ui.tableAvailable.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
        self.ui.tableAvailable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.ui.tableAvailable.horizontalHeader().setCascadingSectionResizes(True)
        self.ui.tableAvailable.horizontalHeader().setStretchLastSection(True)
        self.ui.tableAvailable.verticalHeader().setVisible(False)
        self.ui.tableAvailable.setColumnHidden(0, True)

    def addStuff(self):
        if self.ui.tableAvailable.currentRow() == -1:
            return

        dialog = QtGui.QDialog(self)
        dialog.setWindowTitle("Выбор поставщика")
        dialog.setWindowFlags(QtGui.QWidget.windowFlags(dialog) ^ QtCore.Qt.WindowContextHelpButtonHint)

        buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(dialog.accept)
        buttonBox.rejected.connect(dialog.reject)

        tableProviders = QtGui.QTableWidget(dialog)
        db = self.parent.parent.db
        providers = db.getTable('Поставщики').getAllRows()
        tableProviders.setColumnCount(len(db.getTable('Поставщики').columns))
        tableProviders.setRowCount(len(providers))

        tableProviders.setHorizontalHeaderLabels([item[1] for item in db.getTable('Поставщики').columns])
        tableProviders.setColumnHidden(0, True)
        tableProviders.setEditTriggers(QtGui.QTableWidget.NoEditTriggers)
        tableProviders.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
        tableProviders.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        tableProviders.horizontalHeader().setCascadingSectionResizes(True)
        tableProviders.horizontalHeader().setStretchLastSection(True)
        tableProviders.verticalHeader().setVisible(False)

        i = 0
        for provider in providers:
            j = 0
            for col in provider:
                tableProviders.setItem(i, j, QtGui.QTableWidgetItem(col.__str__()))
                j+=1
            i+=1

        lblCount = QtGui.QLabel('Кол-во', dialog)
        spinCount = QtGui.QSpinBox(dialog)
        spinCount.setMaximum(10000)
        spinCount.setMinimum(1)

        formLayout = QtGui.QFormLayout()
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.addWidget(lblCount)
        horizontalLayout.addWidget(spinCount)
        formLayout.addRow(horizontalLayout)
        formLayout.addRow(tableProviders)
        formLayout.addRow(buttonBox)

        dialog.setLayout(formLayout)
        dialog.exec_()

        if dialog.result() == QtGui.QDialog.Accepted and tableProviders.currentRow() != -1:
            count = self.ui.tableCurrent.rowCount()
            self.ui.tableCurrent.setRowCount(count+1)
            self.ui.tableCurrent.setItem(count, 0, QtGui.QTableWidgetItem(self.ui.tableAvailable.item(self.ui.tableAvailable.currentRow(), 0).text()))
            self.ui.tableCurrent.setItem(count, 1, QtGui.QTableWidgetItem(tableProviders.item(tableProviders.currentRow(), 0).text()))
            self.ui.tableCurrent.setItem(count, 2, QtGui.QTableWidgetItem(self.ui.tableAvailable.item(self.ui.tableAvailable.currentRow(), 1).text()))
            self.ui.tableCurrent.setItem(count, 3, QtGui.QTableWidgetItem(self.ui.tableAvailable.item(self.ui.tableAvailable.currentRow(), 2).text()))
            self.ui.tableCurrent.setItem(count, 4, QtGui.QTableWidgetItem(spinCount.value().__str__()))
            self.ui.tableCurrent.setItem(count, 5, QtGui.QTableWidgetItem(self.ui.tableAvailable.currentRow().__str__()))
            self.ui.tableAvailable.hideRow(self.ui.tableAvailable.currentRow())

    def removeStuff(self):
        if self.ui.tableCurrent.currentRow() == -1:
            return

        self.ui.tableAvailable.showRow(int(self.ui.tableCurrent.item(self.ui.tableCurrent.currentRow(), 5).text()))
        self.ui.tableCurrent.removeRow(self.ui.tableCurrent.currentRow())

    def okAddStuff(self):
        self.parent.stuff = [
            [self.ui.tableCurrent.item(i, j).text() for j in range(0, self.ui.tableCurrent.columnCount())] for i in range(0, self.ui.tableCurrent.rowCount())
        ]
        self.accept()

    def cancel(self):
        self.reject()
